#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <string.h>
#include <pthread.h>

#define PORT    6789
#define BUFF_LEN    1024

void *recvDataThread(void *arg)
{
    int fd = *(int *)arg;
    int size = 0;
    unsigned char buf[BUFF_LEN] = {0};

    printf("fd is %d\n", fd);

    while (true) {
        size = recv(fd, buf, BUFF_LEN, 0);
        buf[size] = '\0';
        if (size > 0) {
            printf("recv: %s\n", buf);
            fflush(stdout);
        }
        send(fd, buf, size, 0);
        usleep(1 * 1000);
    }

    return NULL;
}

void *listenThread(void *arg)
{
    int fd = 0;
    int fdListen = *(int *)arg;
    pthread_t tid;
    
    while (true) {
        struct sockaddr clientAddr;
        int size = sizeof(clientAddr);
        fd = accept(fdListen, (struct sockaddr*)&clientAddr, (socklen_t*)&size);
        if (fd == -1) {
            printf("accept socket error: %s errno: %d\n", strerror(errno), errno);
            continue;
        }
        printf("new client connect: %d\n", fd);
        pthread_create(&tid, NULL, recvDataThread, &fd);

        usleep(1 * 1000);
    }
}

int main(int argc, char *argv[])
{
    struct sockaddr_in sockaddr;
    int port = PORT;
    int fdListen = 0;
    
    memset(&sockaddr, 0, sizeof(sockaddr));
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    sockaddr.sin_port = htons(port);
    fdListen = socket(AF_INET, SOCK_STREAM, 0);

    if (bind(fdListen, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) < 0) {
        printf("Tcp bind errof:%s\n", strerror(errno));
        return 0;
    }
    listen(fdListen, 5);
    pthread_t tid;
    pthread_create(&tid, NULL, listenThread, &fdListen);

    while(1);

    return 0;
}